<template>
  <div class="tags-view-container">
    <div class="tags-view-wrapper">
      <router-link
        v-for="tag in visitedViews"
        :key="tag.path"
        :to="tag.path"
        class="tags-view-item"
        :class="isActive(tag) ? 'active' : ''"
        @contextmenu.prevent="openMenu($event, tag)"
      >
        <el-icon v-if="tag.meta?.icon" class="tag-icon">
          <component :is="tag.meta.icon" />
        </el-icon>
        {{ tag.meta?.title }}
        <el-icon 
          class="close-icon"
          v-if="!isAffix(tag)"
          @click.prevent.stop="closeSelectedTag(tag)"
        >
          <Close />
        </el-icon>
      </router-link>
    </div>

    <!-- 右键菜单 -->
    <ul
      v-show="visible && selectedTag"
      :style="{ left: left + 'px', top: top + 'px' }"
      class="contextmenu"
    >
      <li @click="refreshSelectedTag(selectedTag)">刷新页面</li>
      <li v-if="!isAffix(selectedTag)" @click="closeSelectedTag(selectedTag)">
        关闭当前
      </li>
      <li @click="closeOthersTags(selectedTag)">关闭其他</li>
      <li @click="closeAllTags(selectedTag)">关闭所有</li>
    </ul>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Close } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 固定的标签页
const affixTags = [
  {
    path: '/dashboard',
    name: 'Dashboard',
    meta: { title: '仪表盘', affix: true, icon: 'Odometer' }
  }
]

// 访问过的页面标签
const visitedViews = ref([...affixTags])

// 右键菜单相关
const visible = ref(false)
const left = ref(0)
const top = ref(0)
const selectedTag = ref(null)

// 判断是否是当前激活的标签
const isActive = (tag) => {
  return tag && tag.path === route.path
}

// 判断是否是固定标签
const isAffix = (tag) => {
  return tag && tag.meta && tag.meta.affix === true
}

// 添加标签
const addView = (view) => {
  if (!view || !view.meta?.title) return
  
  const isExists = visitedViews.value.some(v => v.path === view.path)
  if (!isExists) {
    visitedViews.value.push({
      path: view.path,
      name: view.name,
      meta: { ...view.meta }
    })
  }
}

// 关闭标签
const closeSelectedTag = (view) => {
  if (!view) return
  
  const index = visitedViews.value.findIndex(v => v.path === view.path)
  if (index > -1) {
    visitedViews.value.splice(index, 1)
    if (isActive(view)) {
      toLastView(visitedViews.value, view)
    }
  }
  visible.value = false
}

// 关闭其他标签
const closeOthersTags = (view) => {
  if (!view) return
  
  visitedViews.value = visitedViews.value.filter(v => {
    return isAffix(v) || v.path === view.path
  })
  if (!isActive(view)) {
    router.push(view.path)
  }
  visible.value = false
}

// 关闭所有标签
const closeAllTags = (view) => {
  visitedViews.value = visitedViews.value.filter(v => isAffix(v))
  if (view && !isAffix(view)) {
    toLastView(visitedViews.value)
  }
  visible.value = false
}

// 刷新页面
const refreshSelectedTag = (view) => {
  if (!view) return
  
  router.replace({
    path: '/redirect' + view.path
  })
  visible.value = false
}

// 跳转到最后一个标签
const toLastView = (visitedViews, view) => {
  const latestView = visitedViews.slice(-1)[0]
  if (latestView) {
    router.push(latestView.path)
  } else {
    if (view?.name === 'Dashboard') {
      router.replace({ path: '/redirect' + view.path })
    } else {
      router.push('/dashboard')
    }
  }
}

// 打开右键菜单
const openMenu = (e, tag) => {
  if (!tag) return
  
  const menuMinWidth = 105
  const offsetLeft = e.currentTarget.getBoundingClientRect().left
  const offsetWidth = e.currentTarget.offsetWidth
  const maxLeft = window.innerWidth - menuMinWidth
  const left1 = offsetLeft + offsetWidth / 2

  left.value = left1 > maxLeft ? maxLeft : left1
  top.value = e.clientY + 5
  visible.value = true
  selectedTag.value = tag
}

// 点击其他地方关闭右键菜单
const closeMenu = () => {
  visible.value = false
}

// 监听路由变化
watch(
  () => route.path,
  () => {
    if (route.meta?.title) {
      addView(route)
    }
  },
  { immediate: true }
)

onMounted(() => {
  document.addEventListener('click', closeMenu)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', closeMenu)
})
</script>

<style scoped>
.tags-view-container {
  height: 34px;
  width: 100%;
  background: #fff;
  border-bottom: 1px solid #d8dce5;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .12), 0 0 3px 0 rgba(0, 0, 0, .04);
}

.tags-view-wrapper {
  padding: 0 16px;
  height: 100%;
  display: flex;
  align-items: center;
  overflow-x: auto;
  overflow-y: hidden;
  scrollbar-width: none;
}

.tags-view-wrapper::-webkit-scrollbar {
  display: none;
}

.tags-view-item {
  display: inline-flex;
  align-items: center;
  margin-right: 5px;
  padding: 0 8px;
  height: 26px;
  line-height: 26px;
  border: 1px solid #d8dce5;
  color: #495060;
  background: #fff;
  text-decoration: none;
  font-size: 12px;
  border-radius: 3px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.tags-view-item:hover {
  color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

.tags-view-item.active {
  color: #fff;
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
}

.tag-icon {
  margin-right: 4px;
  width: 14px;
  height: 14px;
}

.close-icon {
  margin-left: 4px;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  text-align: center;
  transition: all .3s;
  transform-origin: 100% 50%;
}

.tags-view-item:not(.active) .close-icon:hover {
  color: #fff;
  background-color: var(--el-color-primary);
}

.tags-view-item.active .close-icon:hover {
  color: var(--el-color-primary);
  background-color: #fff;
}

.contextmenu {
  margin: 0;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, .3);
}

.contextmenu li {
  margin: 0;
  padding: 7px 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.contextmenu li:hover {
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

/* 滚动条样式（如果需要显示） */
.tags-view-wrapper {
  scrollbar-width: thin;
  scrollbar-color: var(--el-color-primary-light-5) transparent;
}

.tags-view-wrapper::-webkit-scrollbar {
  height: 4px;
}

.tags-view-wrapper::-webkit-scrollbar-thumb {
  background: var(--el-color-primary-light-5);
  border-radius: 2px;
}

.tags-view-wrapper::-webkit-scrollbar-track {
  background: transparent;
}
</style> 